package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.common.RedisFeign;
import com.fortune.rainshine.feign.common.SmsSendFeign;
import com.fortune.rainshine.feign.service.CityFeign;
import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.CustomerCardFeign;
import com.fortune.rainshine.feign.system.CustomerFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.entity.CustomerEntity;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.SmsParamsModel;
import com.fortune.rainshinecommon.model.system.CustomerServiceTotalModel;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.query.CustomerEditQuery;
import com.fortune.rainshinecommon.util.RandomNumUtil;
import com.fortune.rainshinecommon.util.StringUtil;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("customerController")
public class CustomerController {
    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerFeign customerFeign;
    @Autowired
    private ShopFeign shopFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private RedisFeign redisFeign;
    @Autowired
    private SmsSendFeign smsSendFeign;
    @Value("${smsSend.number}")
    private Integer number;
    @Autowired
    private CustomerCardFeign customerCardFeign;
    @Autowired
    private CityFeign cityFeign;

    //@RequiresPermissions("customer:add")
    @ResponseBody
    @RequestMapping("/add")
    public MsgModel add(@RequestBody CustomerModel model) {
        try{
            if(StringUtils.isBlank(model.getCustomerName())){
                return new MsgModel("顾客姓名不能为空",ResultCode.FAILURE);
            }
            if(StringUtils.isBlank(model.getCustomerPhone())){
                return new MsgModel("顾客电话不能为空",ResultCode.FAILURE);
            }
            if(model.getCustomerSex() == null){
                return new MsgModel("请选择顾客性别",ResultCode.FAILURE);
            }
            if(model.getShopId() == null){
                return new MsgModel("门店信息为空，请重新登录",ResultCode.FAILURE);
            }
            ShopModel shopModel = shopFeign.getShopByShopId(model.getShopId());
            if(shopModel == null){
                return new MsgModel("门店不存在，请重新登录",ResultCode.FAILURE);
            }
            if(model.getCreateId() == null){
                return new MsgModel("操作人信息为空，请重新登录",ResultCode.FAILURE);
            }
            User user = userFeign.getUserById(model.getCreateId());
            if(user == null){
                return new MsgModel("操作人不存在，请重新登录",ResultCode.FAILURE);
            }
            Integer roleId = userFeign.getRoleIdByUserId(model.getCreateId());
            boolean b = (roleId == 5 && model.getCreateId() != shopModel.getManagerId()) || shopModel.getShopLevel() != 3 ||
                    (roleId == 3 && user.getShopId() != model.getShopId());
            if(b){
                return new MsgModel("无添加权限",ResultCode.FAILURE);
            }

            Boolean exists = redisFeign.exists(RedisConstantEnum.ADDCUSTOMER.getMessage() + model.getCustomerPhone());
            if (exists) {
                String sms = (String) redisFeign.get(RedisConstantEnum.ADDCUSTOMER.getMessage() + model.getCustomerPhone()).getData();
                if(sms.equals(model.getVerificationCode())) {
                    redisFeign.delete(RedisConstantEnum.ADDCUSTOMER.getMessage() + model.getCustomerPhone());
                    model.setUser(user);
                    return customerFeign.add(model);
                }else {
                    return new MsgModel("验证码不正确", ResultCode.FAILURE);
                }
            }else {
                return new MsgModel("验证码不存在或者已过期", ResultCode.FAILURE);
            }
        }catch (Exception e){
            logger.error("customerController add ====> {}", e);
            return new MsgModel("添加顾客异常",ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/sms")
    public MsgModel sms(@RequestBody CustomerModel customer) {
        try {
            String phone = customer.getCustomerPhone();
            Boolean exists = redisFeign.exists(RedisConstantEnum.ADDCUSTOMER.getMessage() + phone);
            if (exists) {
                redisFeign.delete(RedisConstantEnum.ADDCUSTOMER.getMessage() + phone);
            }
            Gson gson = new Gson();
            String code = RandomNumUtil.getRandNum(number);
            SmsParamsModel smsParams = new SmsParamsModel();
            smsParams.setCode(code);
            String jsonParams = gson.toJson(smsParams);

            Boolean bo = smsSendFeign.sendSms(phone, jsonParams);
            if (bo) {
                redisFeign.set(RedisConstantEnum.ADDCUSTOMER.getMessage() + phone, code, 60000);
            }
            return new MsgModel(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("CustomerController sms ====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    /**
     * 顾客详情
     * @param customer
     * @return
     */
    @ResponseBody
    @RequestMapping("/customerDetail")
    public MsgModel customerDetail(@RequestBody CustomerModel customer) {
        try {
            CustomerModel customerModel = customerFeign.getCustomer(customer.getId());
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setId(customerModel.getId());
            customerEntity.setCustomerCode(customerModel.getCustomerCode());
            customerEntity.setCustomerName(customerModel.getCustomerName());
            customerEntity.setCustomerPhone(customerModel.getCustomerPhone());
            customerEntity.setCustomerSex(customerModel.getCustomerSex());
            customerEntity.setCustomerBirthday(customerModel.getCustomerBirthday());
            customerEntity.setCustomerPic(customerModel.getCustomerPic());
            customerEntity.setCustomerAddress(customerModel.getCustomerAddress());
            if(StringUtils.isNotBlank(customerModel.getCityCode())){
                customerEntity.setCityCode(customerModel.getCityCode());
                customerEntity.setCityName(cityFeign.getCityNameByCode(customerModel.getCityCode()));
            }
            if(StringUtils.isNotBlank(customerModel.getProvinceCode())){
                customerEntity.setProvinceCode(customerModel.getProvinceCode());
                customerEntity.setProvinceName(cityFeign.getProvinceNameByCode(customerModel.getProvinceCode()));
            }
            customerEntity.setShopId(customerModel.getShopId());
            ShopModel shopModel = shopFeign.getShopByShopId(customerModel.getShopId());
            customerEntity.setShopName(shopModel.getShopName());
            List<CustomerServiceTotalModel> customerCardModelList = customerCardFeign.getListByCustomerId(customerModel.getId());
            customerEntity.setCardModelList(customerCardModelList);
            return new MsgModel(ResultCode.SUCCESS, customerEntity);
        } catch (Exception e){
            logger.error("customerDetail ====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/edit")
    public MsgModel edit(@RequestBody CustomerEditQuery query){
        if(query.getCustomerId() == null){
            return new MsgModel("更新异常",ResultCode.FAILURE);
        }
        CustomerModel customerModel = customerFeign.getCustomer(query.getCustomerId());
        if(customerModel == null){
            return new MsgModel("顾客不存在",ResultCode.FAILURE);
        }
        ShopModel shopModel = shopFeign.getShopByShopId(customerModel.getShopId());
        if(shopModel.getManagerId() != query.getUserId()){
            return new MsgModel("无操作权限",ResultCode.FAILURE);
        }
        if (StringUtil.isNotBlank(query.getCustomerName())) {
            customerModel.setCustomerName(query.getCustomerName());
        }
        if (StringUtil.isNotBlank(query.getPhone())) {
            customerModel.setCustomerPhone(query.getPhone());
        }
        if (StringUtil.isNotBlank(query.getSex())) {
            customerModel.setCustomerSex(Byte.valueOf(query.getSex()));
        }
        if(StringUtil.isNotBlank(query.getPic())){
            customerModel.setCustomerPic(query.getPic());
        }
        if(StringUtil.isNotBlank(query.getCityCode())){
            customerModel.setCityCode(query.getCityCode());
        }
        if(StringUtil.isNotBlank(query.getAddress())){
            customerModel.setCustomerAddress(query.getAddress());
        }
        if(StringUtil.isNotBlank(query.getBirthday())){
            customerModel.setCustomerBirthday(query.getBirthday());
        }
        if(StringUtil.isNotBlank(query.getProvinceCode())){
            customerModel.setProvinceCode(query.getProvinceCode());
        }
        User user = userFeign.getUserById(query.getUserId());
        customerModel.setUser(user);
        return customerFeign.update(customerModel);
    }
}
